package org.flexlancer.databases
{
	import flash.utils.Dictionary;
	
	public class DemandSheetItems
	{
		private static const TABLE:String = "demandsheetitems";

		public static function Add(itemname:String,parentid:Number = -1):void{
			try{
				var insertObj:Object = new Object();
				insertObj.demandsheetitemname = itemname;
				insertObj.demandsheetitemparentid = parentid;
				
				DatabaseManager.Manager.Insert(TABLE,insertObj);
			}catch(err:Error){
				throw err;
			}
		}

		public static function List(condition:String = ""):Array{
			try{
				return DatabaseManager.Manager.Select(TABLE,null,condition,"demandsheetitemname");
			}catch(err:Error){
				throw err;
			}
			return new Array;
		}
		
		public static function ListInXML(condition:String = ""):XML{
			try{
				var arrAll:Array = List(condition);
				var dict:Dictionary = new Dictionary();
				
				for each ( var parentItem:Object in arrAll ){
					if ( parentItem.demandsheetitemparentid == -1 ){
						dict[parentItem.demandsheetitemid] = new XML("<Category id='"+parentItem.demandsheetitemid+"' title='"+parentItem.demandsheetitemname+"' />");
					}
				}

				for each ( var item:Object in arrAll ){
					if ( item.demandsheetitemparentid != -1 ){
						if ( dict [ item.demandsheetitemparentid ] != undefined ){
							dict[item.demandsheetitemparentid].appendChild(new XML("<Item id='"+item.demandsheetitemid+"' title='"+item.demandsheetitemname+"' />"));
						}
					}
				}
				
				var retValue:XML = new XML(<DemandSheetItems />);
				
				var key:String;
				
				for ( key in dict ){
					retValue.appendChild(dict[key]);
				}
				
				return retValue;
			}catch(err:Error){
				throw err;
			}
			return new XML(<DemandSheetItems />);
		}
		
		public static function Delete(condition:String = ""):void{
			try{
				DatabaseManager.Manager.Delete(TABLE,condition);
			}catch(err:Error){
				throw err;
			}
		}
	}
}